package my.util.handler;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by xxb on 2017/9/28.
 */
public class HandlerContext {
    private Map<Object, Object> params = new HashMap<>();
    private HandlerChain handler;
    private Object result;


    public Object getParam(Object key) {
        return params.get(key);
    }

    public <T> T getParam(Object key, Class<T> cls) {
        return cls.cast(params.get(key));
    }

    public String getParamString(Object key) {
        return getParam(key, String.class);
    }

    public HandlerContext addParam(Object key, Object value) {
        params.put(key, value);
        return this;
    }

    public HandlerContext addParams(Map<Object, Object> params) {
        this.params.putAll(params);
        return this;
    }


    public HandlerContext addResult(Object key, Object value) {
        if (result == null) result = new LinkedHashMap<>();
        ((Map) result).put(key, value);
        return this;
    }

    public Object getResult(Object key) {
        if (result == null) return null;
        else if (result instanceof Map) {
            return ((Map) result).get(key);
        } else {
            throw new IllegalArgumentException("result is a not map data structure");
        }
    }

    public <T> T getResult(Object key, Class<T> cls) {
        return cls.cast(getResult(key));
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public HandlerChain getHandler() {
        return handler;
    }

    public void setHandler(HandlerChain handler) {
        this.handler = handler;
    }
}
